//
//  UserCenterViewController.m
//  Contacts
//
//  Created by 李 雷川 on 14-7-17.
//  Copyright (c) 2014年 李 雷川. All rights reserved.
//

#import "UserCenterViewController.h"
#import "Contact.h"
#import "UsercenterHeadCell.h"
#import "UserCenterInfomationCell.h"
#import "Department.h"
#import "ServerInterface.h"
#import "ImageExt.h"
#import "JGProgressHUD.h"
#import "ResetuserInfoController.h"
#import "SignViewController.h"
#import "FeedbackViewController.h"
extern Contact *globalContact;
@interface UserCenterViewController () <UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>{
    IBOutlet UITableView *informationTableView;
}

@property(nonatomic, strong)    UITableView *informationTableView;
@end

@implementation UserCenterViewController
@synthesize informationTableView,contact;
@synthesize headerView,headImageView,nameLabel,headerBgImageView,departmentLabel,positionLabel,logoutBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"个人资料";
    
    self.informationTableView.tableHeaderView = headerView;
    
    
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds),84)];
    footerView.backgroundColor = [UIColor clearColor];
    logoutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *logoutImage = [UIImage imageNamed:@"logout.png"];
    [logoutBtn setBackgroundImage:logoutImage forState:UIControlStateNormal];
    logoutBtn.frame = CGRectMake((CGRectGetWidth(self.view.frame) - logoutImage.size.width)/2,20,logoutImage.size.width,logoutImage.size.height);
    [logoutBtn addTarget:self action:@selector(logout:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:logoutBtn];
    self.informationTableView.tableFooterView = footerView;
    self.informationTableView.showsHorizontalScrollIndicator = NO;
    self.informationTableView.showsVerticalScrollIndicator = NO;
    

    
    [headImageView setContentMode:UIViewContentModeScaleAspectFill];
    [headImageView setClipsToBounds:YES];
    [headImageView.layer setBorderColor:[UIColor whiteColor].CGColor];
    [headImageView.layer setBorderWidth:2.0];
    [headImageView.layer setCornerRadius:headImageView.frame.size.width/2.0];
    
    
    nameLabel.text = globalContact.name;
    departmentLabel.text = globalContact.department.name;
    positionLabel.text = globalContact.position;
    
    NSString *fullImagePath = [IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName];
    if ([[NSFileManager defaultManager]fileExistsAtPath:fullImagePath]) {
        headImageView.image =[UIImage imageWithContentsOfFile:fullImagePath];
    }
    else{
        [headImageView setImageWithURL:[NSURL URLWithString:globalContact.headUrl] placeholderImage:
         [UIImage imageNamed:@"logo.png"] ];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initWithContact:(Contact *)_contact{
    self.contact = _contact;
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
}

-(IBAction)logout:(id)sender{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(IBAction)changePhoto:(id)sender{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"更换头像"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照", @"从相册选择", nil];
    [sheet showFromRect:self.view.bounds inView:self.view animated:YES];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *  cell = nil;
          cell = (UserCenterInfomationCell *)[tableView dequeueReusableCellWithIdentifier:@"InfomationCell"];
    UserCenterInfomationCell *infoCell = (UserCenterInfomationCell *)cell;
    switch (indexPath.row) {
        case 0:{
            infoCell.titleLabel.text = @"手机";
            infoCell.contentLabel.text =globalContact.mobilephone;
            infoCell.logoImageView.image = [UIImage imageNamed:@"telephone_logo.png"];
        }
            break;
        case 1:{
            infoCell.titleLabel.text = @"座机";
            infoCell.contentLabel.text =globalContact.phone;
            infoCell.logoImageView.image = [UIImage imageNamed:@"phone_logo.png"];
        }
            break;
        case 2:{
            infoCell.titleLabel.text = @"办公室";
            infoCell.contentLabel.text =globalContact.officeNo;
            infoCell.logoImageView.image = [UIImage imageNamed:@"office_logo.png"];
        }
            break;
//        case 3:{
//            infoCell.titleLabel.text = @"家乡";
//            infoCell.contentLabel.text =globalContact.name;
//            infoCell.logoImageView.image = [UIImage imageNamed:@"home_logo.png"];
//        }
//            break;
        case 3:{
            infoCell.titleLabel.text = @"工作格言";
            infoCell.contentLabel.text =globalContact.mark;
            infoCell.logoImageView.image = [UIImage imageNamed:@"sign_logo.png"];
        }
            break;
        case 4:{
            infoCell.titleLabel.text = @"反馈和建议";
            infoCell.logoImageView.image = [UIImage imageNamed:@"feedback_logo.png"];
            infoCell.contentLabel.text = @"";
        }
            break;
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
        case 1:
        case 2:{
            ResetuserInfoController *resetuserInfoController = [self.storyboard instantiateViewControllerWithIdentifier:@"ResetuserInfoController"];
            [self.navigationController pushViewController:resetuserInfoController animated:YES];
            resetuserInfoController.viewType = indexPath.row;
            resetuserInfoController.resetUserInfoBlock = ^{
                [informationTableView reloadData];
            };
        }
            break;
        case 3:{
            SignViewController *signViewController= [self.storyboard instantiateViewControllerWithIdentifier:@"SignViewController"];
            [self.navigationController pushViewController:signViewController animated:YES];
            signViewController.resetUserInfoBlock = ^{
                [informationTableView reloadData];
            };
        }
            break;
        case 4:{
            FeedbackViewController *feedbackViewController= [self.storyboard instantiateViewControllerWithIdentifier:@"FeedbackViewController"];
            [self.navigationController pushViewController:feedbackViewController animated:YES];
        }
            break;
        default:
            break;
    }


}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
}


#pragma mark
#pragma mark UIActionSheetDelegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate =self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:^{
        }];
        
    }
    else if (buttonIndex == 1) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate =self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:^{
        }];

       
    }

}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet{
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    
}

#pragma mark
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //如果是 来自照相机的image，那么先保存
        UIImage* original_image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        UIImageWriteToSavedPhotosAlbum(original_image,nil,nil,
                                       nil);
    }
    
    //获得编辑过的图片
    UIImage* image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
    [self uploadPhotoWithImage:image];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)uploadPhotoWithImage:(UIImage *)image{
   JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleExtraLight];
    HUD.textLabel.text = @"正在上传";
    [HUD showInView:self.view];
    
   image = [image scaleToSize:image size:CGSizeMake(image.size.width/3,image.size.height/3)];
    NSDictionary *paramDic = @{@"company_id":CompanyID,@"token":globalContact.token,@"user_id":@(globalContact.userID)};
    if (![[NSFileManager defaultManager] fileExistsAtPath:IMAGE_FORDER isDirectory:nil]) {
        [[NSFileManager defaultManager]createDirectoryAtPath:IMAGE_FORDER withIntermediateDirectories:YES attributes:nil error:nil];
    }
    double time = [[NSDate date]timeIntervalSince1970];
    NSString *imageName =[NSString stringWithFormat:@"%ld.png",(long)time];
    NSString *filePath =[IMAGE_FORDER stringByAppendingPathComponent:imageName];
    BOOL success = [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
    
    if (success) {
        [[NSFileManager defaultManager]removeItemAtPath:[IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName] error:nil];

        [ServerInterface uploadHeadWithDic:paramDic withFileName:imageName withBlock:^(NSDictionary *headDic, NSError *error) {
            NSLog(@"headDic is:%@",headDic);
            if (error) {
                NSLog(@"error is:%@",error);
            }
            else{
                if ([[headDic valueForKeyPath:@"success"] boolValue]) {
                    globalContact.headName = imageName;
                    headImageView.image =[UIImage imageWithContentsOfFile:filePath];
//                    [self updateCellHeadImage];
                    [Contact updateContact:contact];
                }
                else{
                }
            }
            [HUD dismissAfterDelay:1.0 animated:YES];
        }];
    }

}

-(void)updateCellHeadImage{
    UserCenterHeadCell *headCell =(UserCenterHeadCell *) [informationTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    headCell.headImageView.image =[UIImage imageWithContentsOfFile: [IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName]];
}
@end
